package com.cnswhy.cloud.server.app.controller.customer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.BeanPlusUtil;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.core.utils.SystemClockUtil;
import com.cnswhy.cloud.common.logging.uitls.MDCUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.core.utils.PasswordCoder;
import com.cnswhy.cloud.server.app.utils.RSAUtils;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.TransType;
import com.cnswhy.cloud.server.common.entity.enumeration.WalletType;
import com.cnswhy.cloud.server.common.entity.mq.WithdrawRecordMQ;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dto.WithdrawalRecordSaveDTO;
import com.cnswhy.cloud.server.core.entity.Customer;
import com.cnswhy.cloud.server.core.entity.CustomerWallet;
import com.cnswhy.cloud.server.core.entity.SysConfig;
import com.cnswhy.cloud.server.core.entity.WithdrawalRecord;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.SysConfigService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.service.trans.WithdrawalRecordService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import com.cnswhy.cloud.server.core.wallet.WalletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@Api(tags = "用户提现控制层")
@Controller
@RequestMapping("/withdrawl")
@Slf4j
public class WithdrawlController extends BaseController {

    @Autowired
    private WithdrawalRecordService withdrawlService;
    @Autowired
    IdGeneratorService idGeneratorService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CustomerService customerService;
    @Autowired
    MessageService messageService;
    @Autowired
    WalletService walletService;
    @Autowired
    SysConfigService sysConfigService;

    @ApiOperation(value = "保存提现记录", httpMethod = "POST")
    @ApiParam(name = "entity", value = "提现记录实体")
    @RequestMapping("/saveData")
    @ResponseBody
    public RespVo saveData(WithdrawalRecordSaveDTO entity, HttpServletRequest request) {
        log.info("保存提现记录：{} {} {}", JSON.toJSONString(entity));

        RespVo vo = new RespVo();
        try {
            //先判空交易密码
            if (StringUtils.isBlank(entity.getPayPassword())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("交易密码为空");
                return vo;
            }

            Customer loginCustomer = getLoginCustomer( request);
            Customer customer = customerService.queryById(loginCustomer.getId());

            String passwd = RSAUtils.decryptString(entity.getPayPassword());//解密


            //交易密码验证
            if (!(PasswordCoder.validatePassword(customer.getTradePass(), passwd))) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("交易密码错误");
                return vo;
            }

            String rate = "";
            SysConfig sysConfigAmt = sysConfigService.getOne(Wraps.<SysConfig>lbQ().eq(SysConfig::getConfigKey, "wallet_amt"));
            if (entity.getAmount().compareTo(new BigDecimal(sysConfigAmt.getConfigValue())) == -1) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("最低转出金额为" + sysConfigAmt.getConfigValue());
                return vo;
            }
            if(entity.getType() == 2 || entity.getType() == 3){
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("目前仅支持银行卡提现");
                return vo;
            }
            /*if(!"1".equals(entity.getType())){
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("目前仅支持银行卡提现");
                return vo;
            }*/

            BigDecimal[] divideAndRemainder = entity.getAmount().divideAndRemainder(new BigDecimal(10));
            /*
            if (divideAndRemainder[0].compareTo(BigDecimal.ZERO) <= 0) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("提现金额必须大于100");
                return vo;
            }*/
            /*if (divideAndRemainder[1].compareTo(BigDecimal.ZERO) != 0) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("提现金额必须为10的整数倍");
                return vo;
            }*/
            /*if (customer.getAvailableBalance().compareTo(entity.getAmount()) < 0) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("可用余额不足");
                return vo;
            }*/
            rate = (String) redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.BALANCE_WITHDRAW_SERVICE);
            String orderId = idGeneratorService.genCommonIdString();
            CustomerWallet customerWallet = walletService.checkAndCreate(customer.getId(), WalletType.BALANCE, 0L);
            if(!walletService.checkDed(customerWallet.getCustomerId(),WalletType.BALANCE,CnswhyUtil.getFen(entity.getAmount()))){
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("可用余额不足");
                return vo;
            }
            walletService.fronzen(customerWallet.getCustomerId(),WalletType.BALANCE, TransType.WITHDRAW,CnswhyUtil.getFen(entity.getAmount()),TransType.WITHDRAW.getCode() + orderId);

            //BigDecimal serviceMoney = entity.getAmount().multiply(new BigDecimal(rate)).add(BigDecimal.valueOf(2.0));
            BigDecimal serviceMoney = BigDecimal.ONE.add(BigDecimal.ONE)  ;
            entity.setRealPay(entity.getAmount().subtract(serviceMoney));
            entity.setVerifyStatus(1);
            entity.setStatus(1);
            entity.setCustomerId(loginCustomer.getId());
            entity.setOrderNum(orderId);
            //dto转entity 入库
            WithdrawalRecord withdrawalRecord = BeanPlusUtil.toBean(entity, WithdrawalRecord.class);
            withdrawalRecord.setCreateTime(SystemClockUtil.getLocalDateTime());
            withdrawalRecord.setUpdateTime(withdrawalRecord.getCreateTime());
            withdrawlService.save(withdrawalRecord);
            try {
                WithdrawRecordMQ withdrawRecordMQ = WithdrawRecordMQ.builder().id(withdrawalRecord.getId()).build();
                withdrawRecordMQ.setTraceId(MDCUtil.getTraceId());
                messageService.sendQueueByObject(AmqpExchange.CREATE_WITHDRAW_MESSAGE, withdrawRecordMQ);
            } catch (IllegalArgumentException e) {
                log.info("mq error");
            }
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("保存成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("提现失败");
            log.error("提现失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "分页查询提现记录", httpMethod = "POST")
    @ApiParam(name = "bo", value = "提现记录BO")
    @RequestMapping("/ajaxPageData")
    @ResponseBody
    public RespVo ajaxPageData(WithdrawalRecord bo,
                               @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("分页查询提现记录：{} {} {}", JSON.toJSONString(bo), currentPage, pageSize);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            bo.setCustomerId(loginCustomer.getId());
            QueryWrapper<WithdrawalRecord> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByDesc("create_time");
            Page<WithdrawalRecord> page = new Page<>(currentPage, pageSize);
            IPage<WithdrawalRecord> pageList = withdrawlService.page(page, queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询失败", e);
        }
        return vo;
    }

    public static void main(String[] args) throws Exception {
        String pass = "a21e903af80c14b5ea456a15f915b9b4632795c258bf84ecf3234bafa2fe298f7527477de61fce3e568ab01aff81c42c887f951b9c71ccf57b69fe76b601f1d84fa52413664821c550a08f60a832bff579e1e601ed1e5a4adf5a5014acea0a780a1e7b66d2285973e04205e448ee0c42d362958b30cfd4f80d11562175441a64";
        String pass1 = RSAUtils.decryptString(pass);

        Boolean c = PasswordCoder.validatePassword("-49E26696BCDB0CA9F187A5A127BF356A28AA015E", pass1);

        String pass2 = PasswordCoder.generatePassword("123456");
        pass1 = PasswordCoder.encodeByMD5(pass1);
        System.out.println(pass1);
        System.out.println(c);
        System.out.println(pass2);
        System.out.println(SystemClockUtil.getLocalDateTime());
    }
}
